package com.bbs.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bbs.pojo.Message;
import com.bbs.pojo.dto.MessageDto;
import com.bbs.pojo.Result;
import com.bbs.pojo.UserPrincipal;
import com.bbs.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/api")
public class MessageController {
    @Autowired
    private MessageService messageService;

    @GetMapping("/messages")
    @PreAuthorize("isAuthenticated()")
    public Result<List<MessageDto>> getMessages(@AuthenticationPrincipal UserPrincipal user){
        return Result.succeed(messageService.getMessagesByReceiver(user.getUserId()));
    }

    @GetMapping("/messages/unacknowledged/count")
    @PreAuthorize("isAuthenticated()")
    public Result<Long> getUnacknowledgedMessageCount(@AuthenticationPrincipal UserPrincipal user){
        return Result.succeed(messageService.acknowledgedMessageCountByReceiver(user.getUserId()));
    }

    @PostMapping("/messages/acknowledge")
    @PreAuthorize("isAuthenticated()")
    public Result<Object> acknowledgeMessage(@RequestBody List<String> messageIds, @AuthenticationPrincipal UserPrincipal user) {
        return Result.build(messageService.acknowledgeMessage(user.getUserId(), messageIds));
    }

    /**
     * 确认某时刻之前的所有消息（除用户私信消息）
     * @param time
     * @param user
     * @return
     */
    @PostMapping("/messages/acknowledge/before/{time}")
    @PreAuthorize("isAuthenticated()")
    public Result<Object> acknowledgeMessageBefore(@PathVariable("time") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime time,
                                                   @AuthenticationPrincipal UserPrincipal user){
        return Result.build(messageService.acknowledgeMessageBefore(user.getUserId(), time));
    }

    //不对外开放---------------------------------
    @GetMapping("/sys/messages/search")
    public Result<List<Message>> getMessages(@AuthenticationPrincipal UserPrincipal user, @RequestBody Message message){
        return Result.succeed(messageService.list(new QueryWrapper<>(message)));
    }

    @GetMapping("/sys/messages/{id}")
    public Result<MessageDto> getMessage(@PathVariable("id") String id){
        return Result.withData(messageService.getMessageById(id));
    }

    @DeleteMapping("/sys/messages/{id}")
    public Result<Object> removeMessage(@PathVariable("id") String id){
        return Result.build(messageService.removeById(id));
    }
}
